package com.cskaoyan.order.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cskaoyan.mall.commons.result.ResponseData;
import com.cskaoyan.mall.commons.result.ResponseUtil;
import com.cskaoyan.mall.order.constant.OrderRetCode;
import com.cskaoyan.order.dto.OrderDetailRequest;
import com.cskaoyan.order.dto.OrderDetailResponse;
import com.cskaoyan.order.dto.OrderListRequest;
import com.cskaoyan.order.dto.OrderListResponse;
import com.cskaoyan.order.form.PageResponse;
import com.cskaoyan.order.service.OrderQueryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

/**
 * @author pjr
 * @version 1.0.0
 * @description TODO
 * @date 2022/6/17 20:39
 */
@RestController
@RequestMapping("/shopping")
public class OrderQueryController {
    @Autowired
    OrderQueryService orderQueryService;


    /**
     * 查询所有订单
     * @param request
     * @param httpServletRequest
     * @return
     */
    @GetMapping("/order")
    public ResponseData orderList(OrderListRequest request, HttpServletRequest httpServletRequest) {
        // 获取userId
        String userInfo = (String) httpServletRequest.getHeader("user_info");
        JSONObject object = JSON.parseObject(userInfo);
        Long uid = Long.parseLong(object.get("uid").toString());
        request.setUserId(uid);
        OrderListResponse response = orderQueryService.orderList(request);

        PageResponse pageResponse = new PageResponse();
        pageResponse.setData(response.getDetailInfoList());
        pageResponse.setTotal(response.getTotal());
        if (response.getCode().equals(OrderRetCode.SUCCESS.getCode())) {
            return new ResponseUtil<>().setData(pageResponse);
        }
        return new ResponseUtil<>().setErrorMsg(response.getMsg());
    }

    /**
     * 查询订单详情
     * @param id
     * @return
     */
    @GetMapping("/order/{id}")
    public ResponseData getOrderDetail(@PathVariable("id") String id, HttpServletRequest servletRequest) {

        OrderDetailRequest request = new OrderDetailRequest();

        request.setOrderId(id);

        // 调用service处理请求
        OrderDetailResponse response = orderQueryService.orderDetail(request,servletRequest);

        if (OrderRetCode.SUCCESS.getCode().equals(response.getCode())) {
            // 执行成功，直接返回前端需要的数据
            return new ResponseUtil<>().setData(response);
        }
        // 调用失败
        return new ResponseUtil<>().setErrorMsg(response.getMsg());
    }



}
